<?php
class v1_flux{
	private $chart=array(
		'bg_colour'=>'#FFFFFF',
		'x_axis'=>array(
			'colour'=>'#AAAAAA','steps'=>1,'grid-colour'=>'#EEEEEE','stroke'=>1,'tick-height'=>4,'labels'=>array('labels'=>array(),'rotate'=>30)
		),
		'elements'=>array(),
		'tooltip'=>array('stroke'=>1,'colour'=>'#000000','background'=>'#FFFBCA')
	);
	private $metrics=array();
	private $dimensions=array();
	function init(){
    	$cache=$this->yum->cache(array('tag'=>'dimensions.metrics','time'=>86400,'path'=>'flux'));
    	if($cache===false){
    		$sort=$this->yum->model('sort');
	    	$this->metrics['chart']=$sort->GSort(array('select'=>'id,name,value','order'=>array('sequence'=>'desc'),'where'=>array('label='=>'metrics.chart')));
	    	$this->metrics['table']=$sort->GSort(array('select'=>'id,name,value','order'=>array('sequence'=>'desc'),'where'=>array('label='=>'metrics.table')));
	    	$this->dimensions=$sort->GSort(array('select'=>'id,name,value','order'=>array('sequence'=>'desc'),'where'=>array('label='=>'dimensions')));
	    	$this->yum->cache(array('content'=>serialize(array('metrics'=>$this->metrics,'dimensions'=>$this->dimensions)),'tag'=>'dimensions.metrics','time'=>86400,'path'=>'flux'));
    	}else{
    		$cache=unserialize($cache);
    		$this->metrics=$cache['metrics'];
    		$this->dimensions=$cache['dimensions'];
    	}
	}
    function index(){
    	$action=$this->yum->get('action');$pams=array();
    	$data['date']['start']=$this->yum->get('start');$data['date']['end']=$this->yum->get('end');
    	if(empty($data['date']['start'])||empty($data['date']['end'])){
    		$data['date']['start']=date('Y-m-d',strtotime("-30 day"));
    		$data['date']['end']=date('Y-m-d');$cache['order']=$data['order']='click';$cache['by']=$data['by']='desc';
    	}
    	$pams['start']=strtotime($data['date']['start']);$pams['end']=strtotime($data['date']['end']);
    	if($action=='chart'){
    		$data['metrics_chart']=intval($this->yum->get('metrics_chart'));
    		if(!isset($this->metrics['chart'][$data['metrics_chart']])){
    			$data['metrics_chart']=key($this->metrics['chart']);
    		}
    		$pams['select'][]=$this->metrics['chart'][$data['metrics_chart']];
    		$data['contrast']=intval($this->yum->get('contrast'));
    		if(isset($this->metrics['chart'][$data['contrast']])){
    			$pams['select'][]=$this->metrics['chart'][$data['contrast']];
    		}
    		$data['type']=$this->yum->get('type');
    		if(!in_array($data['type'],array('day','week','month'))){
    			$data['type']='day';
    		}
    		if($data['type']=='week'){
    			$pams['start']=intval(date('Ymd',$pams['start']-intval(date('N',$pams['start']))*86400+86400));
    			$pams['end']=intval(date('Ymd',$pams['end']-intval(date('N',$pams['end']))*86400+86400));
    		}else if($data['type']=='month'){
    			$pams['start']=intval(date('Ym',$pams['start']));
    			$pams['end']=intval(date('Ym',$pams['end']));
    		}
			$data=$this->chart($pams);
			header('Content-Type:text/plain');
			echo json_encode($data);
    	}else{
    		$data['basic']=domain.'index.php?c=flux&a=index&action=table';
    		$data['basic'].='&start='.$data['date']['start'].'&end='.$data['date']['end'];
    		$temp=$this->yum->get('dimensions');
    		if(empty($temp)){
    			$data['sdim']=array_slice($this->dimensions,0,1,true);
    		}else{
    			foreach($temp as $value){
    				$value=intval($value);$T=$this->dimensions[$value];
    				if(isset($T)){
    					$data['sdim'][$value]=$T;
    				}
    			}
    		}
  			$pams['dimensions']=$data['sdim'];
    		$temp=$this->yum->get('metrics_table');
    		if(empty($temp)){
    			$data['smet']=array_slice($this->metrics['table'],0,5,true);
    		}else{
    			foreach($temp as $value){
    				$value=intval($value);$T=$this->metrics['table'][$value];
    				if(isset($T)){
    					$data['smet'][$value]=$T;
    				}
    			}
    		}
    		$pams['metrics']=$data['smet'];
    		$data['order']=intval($this->yum->get('order'));$data['rule']=strtolower($this->yum->get('rule'));
    		if(!in_array($data['rule'],array('desc','asc'))){
    			$data['rule']='desc';
    		}
    		if(isset($this->dimensions[$data['order']])){
    			$pams['order']=$this->dimensions[$data['order']];
    		}else if(isset($this->metrics['table'][$data['order']])){
    			$pams['order']=$this->metrics['table'][$data['order']];
    		}else{
    			$data['order']=key($pams['metrics']);$pams['order']=$this->metrics['table'][$data['order']];
    		}
    		$pams['order']=$pams['order']['value'];$pams['rule']=$data['rule'];
    		$pams['offset']=$data['offset']=intval($this->yum->get('offset'));$pams['length']=15;
			$temp=$this->table($pams);
			$data['table']=$temp['table'];$data['total']=$temp['total']['rows'];
	    	$pagination=$this->yum->library('pagination',array('query_string'=>'offset','base_url'=>$data['basic'].'&order='.$data['order'].'&rule='.$data['rule'],'total_rows'=>$data['total'],'per_page'=>$pams['length'],'first_link'=>'首页','last_link'=>'末页','cur_tag_open'=>'<a href="#" class="active">','cur_tag_close'=>'</a>'));
			$data['pagination']=$pagination->create_links();
			if($action=='table'){
				$this->yum->set($data);$this->yum->view('table.php',array('strip'=>true));
	    		$html=$this->yum->fetch('');header('Content-Type:text/plain');
				echo json_encode(array('html'=>$html));
			}else{
				$data['metrics_chart']=intval($this->yum->get('metrics_chart'));
	    		if(!isset($this->metrics['chart'][$data['metrics_chart']])){
	    			$data['metrics_chart']=key($this->metrics['chart']);
	    		}
	    		$data['contrast']=intval($this->yum->get('contrast'));
	    		if(!isset($this->metrics['chart'][$data['contrast']])){
	    			$data['contrast']=0;
	    		}
	    		$data['type']=$this->yum->get('type');
	    		if(!in_array($data['type'],array('day','week','month'))){
	    			$data['type']='day';
	    		}
				$data['ghb']=$temp['total'];
				$data['metrics']=$this->metrics;$data['dimensions']=$this->dimensions;
				$this->yum->set($data);
	    		$this->yum->view('index.php');
			}
    	}
    }
    function excel(){
    	$action=$this->yum->get('action');$pams=array();
    	$start=$this->yum->get('start');$end=$this->yum->get('end');
    	$pams['chart']['start']=strtotime($start);$pams['chart']['end']=strtotime($end);
    	$pams['chart']['select'][]=$this->metrics['chart'][intval($this->yum->get('metrics_chart'))];
    	$contrast=intval($this->yum->get('contrast'));
    	if(isset($this->metrics['chart'][$contrast])){
    		$pams['chart']['select'][]=$this->metrics['chart'][$contrast];
    	}
    	$type=$this->yum->get('type');
    	if($type=='week'){
    		$pams['chart']['start']=intval(date('Ymd',$start-intval(date('N',$start))*86400+86400));
    		$pams['chart']['end']=intval(date('Ymd',$end-intval(date('N',$end))*86400+86400));
    	}else if($type=='month'){
    		$pams['chart']['start']=intval(date('Ym',$start));
    		$pams['chart']['end']=intval(date('Ym',$end));
    	}

    	$pams['table']['start']=strtotime($start);$pams['table']['end']=strtotime($end);
    	$temp=$this->yum->get('dimensions');
    	foreach($temp as $value){
    		$value=intval($value);$T=$this->dimensions[$value];
    		if(isset($T)){
    			$pams['table']['dimensions'][$value]=$T;
    		}
    	}
    	$temp=$this->yum->get('metrics_table');
    	foreach($temp as $value){
    		$value=intval($value);$T=$this->metrics['table'][$value];
    		if(isset($T)){
    			$pams['table']['metrics'][$value]=$T;
    		}
    	}
    	$pams['table']['order']=intval($this->yum->get('order'));$pams['table']['rule']=strtolower($this->yum->get('rule'));$pams['table']['length']=true;
		$chart=$this->chart($pams['chart']);
		$table=$this->table($pams['table']);
		$excel=$this->yum->library('PHPExcel');
		$excel->getProperties()->setTitle("Office 2007 XLSX Document");
		$excel->getProperties()->setSubject("Office 2007 XLSX Document");
		$excel->getProperties()->setDescription("document for Office 2007 XLSX, generated using phpexcel.");
		$excel->setActiveSheetIndex(0);
		$excel->getActiveSheet()->getPageMargins()->setTop(0);
		$excel->getActiveSheet()->getPageMargins()->setRight(0.6);
		$excel->getActiveSheet()->getPageMargins()->setLeft(0.6);
		$excel->getActiveSheet()->getPageMargins()->setBottom(0);
		$objActSheet=$excel->getActiveSheet();
		$objActSheet->setTitle('趋势图');$objActSheet->setCellValueByColumnAndRow(0,1,'日期');
		foreach($pams['chart']['select'] as $key=>$value){
			$objActSheet->setCellValueByColumnAndRow($key+1,1,$value['name']);
		}
		$line=2;
		foreach($chart['x_axis']['labels']['labels'] as $key=>$value){
			$objActSheet->setCellValueByColumnAndRow(0,$line,$value);
			$objActSheet->setCellValueByColumnAndRow(1,$line,$chart['elements'][0]['values'][$key]);
			$objActSheet->setCellValueByColumnAndRow(2,$line,$chart['elements'][1]['values'][$key]);
			$line++;
		}
		$excel->createSheet();$excel->setActiveSheetIndex(1);$objActSheet=$excel->getActiveSheet();
		$objActSheet->setTitle('维度&指标');$rows=0;
		foreach($pams['table']['dimensions'] as $value){
			$objActSheet->setCellValueByColumnAndRow($rows,1,$value['name']);
			$rows++;
		}
		foreach($pams['table']['metrics'] as $value){
			$objActSheet->setCellValueByColumnAndRow($rows,1,$value['name']);
			$rows++;
		}
		$line=2;
		foreach($table['table'] as $value){
			$rows=0;
			foreach($pams['table']['dimensions'] as $v){
				$objActSheet->setCellValueByColumnAndRow($rows,$line,$value[$v['value']]);
				$rows++;
			}
			foreach($pams['table']['metrics'] as $v){
				$objActSheet->setCellValueByColumnAndRow($rows,$line,$value[$v['value']]);
				$rows++;
			}
			$line++;
		}
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="'.(date('Y-m-d').'-flux-'.rand()).'.xlsx"');
		header('Cache-Control: max-age=0');
		$objWriter=PHPExcel_IOFactory::createWriter($excel,'Excel2007');
		$objWriter->save('php://output');
    }
    function chart($pams){
    	$cache=$this->yum->cache(array('tag'=>'flux.chart,'.$pams['start'].$pams['end'],'time'=>300,'path'=>'flux'));
    	if($cache===false){
			$chart=$this->yum->model('data');
			$cache=$chart->select('chart',array('where'=>array('date>='=>$pams['start'],'date<='=>$pams['end']),'order'=>array('date'=>'ASC')));
			foreach($cache as $key=>$value){
				if($value['date']>=1000000000){
					$cache[$key]['date']=date('m/d',$value['date']);
				}elseif($value['date']>=10000000){
					$value['date']=strtotime($value['date']);
					$cache[$key]['date']=date('m/d',$value['date']).'-'.date('m/d',$value['date']+518400);
				}else{
					$cache[$key]['date']=date('Y/m',strtotime($value['date'].'01'));
				}
				$cache[$key]['crate']=floor($value['click']/$value['impression']*10000)/100;
				$cache[$key]['rrate']=floor($value['reach']/$value['impression']*10000)/100;
				$cache[$key]['trate']=floor($value['transform']/$value['impression']*10000)/100;
				$cache[$key]['vcrate']=floor($value['cvisitor']/$value['ivisitor']*10000)/100;
				$cache[$key]['vrrate']=floor($value['rvisitor']/$value['ivisitor']*10000)/100;
				$cache[$key]['vtrate']=floor($value['tvisitor']/$value['ivisitor']*10000)/100;
				$cache[$key]['iaverage']=intval($value['fee']/$value['impression']*100)/100;
				$cache[$key]['caverage']=intval($value['fee']/$value['click']*100)/100;
			}
			$this->yum->cache(array('content'=>serialize($cache),'tag'=>'flux.chart,'.$pams['start'].$pams['end'],'path'=>'flux'));
    	}else{
    		$cache=unserialize($cache);
    	}
		//缓存数据
		$line=array();
		if(empty($cache)){
			$this->chart['x_axis']['labels']['labels']=array();
			$line=array(array(),array());
		}else{
			foreach($cache as $key=>$value){
				$this->chart['x_axis']['labels']['labels'][]=$value['date'];
				foreach($pams['select'] as $k=>$v){
					$line[$k][]=floatval($value[$v['value']]);
				}
			}
		}
		$M=count($this->chart['x_axis']['labels']['labels']);
		if($M>20){
			$this->chart['x_axis']['labels']['steps']=floor($M/20);
		}
		$M=reset($line);$M=max($M);$M=$M>100?(ceil($M/10)*10):100;$steps=floor($M/2);$N=reset($pams['select']);
		$this->chart['y_axis']=array('colour'=>'#aaaaaa','grid-colour'=>'#eeeeee','stroke'=>1,'tick-length'=>5,'min'=>0,'max'=>$M,'steps'=>$steps);
		$this->chart['elements'][]=array('type'=>'line','fill-alpha'=>0.4,'width'=>2,'dot-style'=>array('type'=>'solid-dot','tip'=>$N['name'].': #val#<br>#x_label#'),'dot-size'=>1,'halo-size'=>2,'colour'=>'#FF9900','values'=>reset($line));
		if(count($line)==2){
			$M=end($line);$M=max($M);$M=$M>100?(ceil($M/10)*10):100;$steps=floor($M/2);$N=end($pams['select']);
			$this->chart['y_axis_right']=array('colour'=>'#aaaaaa','grid-colour'=>'#eeeeee','stroke'=>1,'tick-length'=>5,'min'=>0,'max'=>$M,'steps'=>$steps);
			$this->chart['elements'][]=array('type'=>'line','axis'=>'right','fill-alpha'=>0.4,'width'=>2,'dot-style'=>array('type'=>'solid-dot','tip'=>$N['name'].': #val#<br>#x_label#'),'dot-size'=>1,'halo-size'=>2,'colour'=>'#356aa0','values'=>end($line));
		}
		return $this->chart;
    }
    function table($pams){
    	$data=array();$total=array();
    	foreach($pams['dimensions'] as $value){
	    	$dimensions[]='`'.$value['value'].'`';
	    }
    	$cache=$this->yum->cache(array('tag'=>'flux.'.implode(',',$dimensions).$pams['start'].$pams['end'],'time'=>300,'path'=>'flux'));
    	if($cache===false){
	    	$table=$this->yum->model('data');
			$cache['data']=$table->select('table',array('select'=>implode(',',$dimensions).',SUM(impression) AS impression,SUM(click) AS click,SUM(reach) AS reach,SUM(transform) AS transform,SUM(shop) AS shop,SUM(fee) AS fee','group'=>implode(',',$dimensions),'where'=>array('date>='=>$pams['start'],'date<='=>$pams['end'])));
			foreach($cache['data'] as $key=>$value){
				$cache['total']['impression']+=$value['impression'];
				$cache['total']['click']+=$value['click'];
				$cache['total']['reach']+=$value['reach'];
				$cache['total']['transform']+=$value['transform'];
				$cache['total']['shop']+=$value['shop'];
				$cache['total']['fee']+=$value['fee'];
				$cache['data'][$key]['crate']=floor($value['click']/$value['impression']*10000)/100;
				$cache['data'][$key]['rrate']=floor($value['reach']/$value['impression']*10000)/100;
				$cache['data'][$key]['trate']=floor($value['transform']/$value['impression']*10000)/100;
				$cache['data'][$key]['iaverage']=intval($value['fee']/$value['impression']*100)/100;
				$cache['data'][$key]['caverage']=intval($value['fee']/$value['click']*100)/100;
				$order[]=$cache['data'][$key][$pams['order']];
			}
			if(isset($pams['order'])&&isset($pams['rule'])){
				$cache['order']=$pams['order'];$cache['rule']=$pams['rule'];
				array_multisort($order,$pams['rule']=='asc'?SORT_ASC:SORT_DESC,$cache['data']);
			}
			$cache['total']['rows']=count($cache['data']);
			$this->yum->cache(array('content'=>serialize($cache),'tag'=>'flux.'.implode(',',$dimensions).$pams['start'].$pams['end'],'path'=>'flux'));
    	}else{
    		$cache=unserialize($cache);
    		if($pams['order']!=$cache['order']||$pams['rule']!=$cache['rule']){
    			$cache['order']=$pams['order'];$cache['rule']=$pams['rule'];
    			foreach($cache['data'] as $value){
    				$order[]=$value[$pams['order']];
    			}
    			array_multisort($order,$pams['rule']=='asc'?SORT_ASC:SORT_DESC,$cache['data']);
    			$this->yum->cache(array('content'=>serialize($cache),'tag'=>'flux.'.implode(',',$dimensions).$pams['start'].$pams['end'],'path'=>'flux'));
    		}
    	}
    	$total=$cache['total'];$data=$cache['data'];
		//缓存数据
		if($pams['length']===true){
			$temp=$data;unset($data);
		}else{
			$temp=array_slice($data,$pams['offset'],$pams['length']);unset($data);
		}
		foreach($temp as $key=>$value){
			foreach($pams['dimensions'] as $k=>$v){
				if($v['value']=='date'||$v['value']=='version'||$v['value']=='screen'){
					switch($v['value']){
						case 'date':
						$value[$v['value']]=date('Y-m-d',$value[$v['value']]);
						break;
						case 'screen':
						$value[$v['value']]=floor($value[$v['value']]/100000).'*'.($value[$v['value']]%100000);
						break;
					}
				}else{
					$CH[$v['value']][$value[$v['value']]]=$value[$v['value']];
				}
				$data[$key][$v['value']]=$value[$v['value']];
			}
			foreach($pams['metrics'] as $v){
				$T=$value[$v['value']];
				$data[$key][$v['value']]=empty($T)?0:$T;
			}
		}
		if(!empty($CH)){
			$name=$this->yum->model('name');
			$CH=$name->select($CH);
			foreach($data as $key=>$value){
				foreach($pams['dimensions'] as $v){
					if($v['value']!='date'&&$v['value']!='version'&&$v['value']!='screen'){
						$T=$CH[$v['value']][$value[$v['value']]]['name'];
						$value[$v['value']]=empty($T)?'未知':$T;
					}
				}
				$data[$key]=$value;
			}
		}
		return array('table'=>$data,'total'=>$total);
    }
}
?>